<!--案件受理 受理交办弹窗-->

<template>
  <el-dialog append-to-body title="案件派发" width="60%" :visible="visible" @close="handleClose">
    <el-form ref="form" :model="form" :rules="rules" label-suffix="：" label-width="140px" class="white-card">
      <el-form-item label="承办类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="0">直办</el-radio>
          <el-radio :label="1">转办</el-radio>
          <el-radio :label="2">交办</el-radio>
          <el-radio :label="3">指定办理</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item label="案件类型" prop="itemCode">
        <el-select v-model="form.itemCode" placeholder="请选择" style="width: 100%">
          <el-option-group
            v-for="group in itemdetailTree"
            :key="group.label"
            :label="group.label">
            <el-option
              v-for="item in group.options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item> -->

      <el-form-item v-if="[1].includes(form.type)" :label="typeLabel + '部门'" prop="processDepartmentCode">
        <el-cascader
          ref="cascader"
          v-model="form.processDepartmentCode"
          :props="{ label: 'name', value: 'code', expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
          :options="departmentTree"
          :show-all-levels="false"
          @change="$refs.cascader && $refs.cascader.toggleDropDownVisible(false)"
          style="width: 100%"
          placeholder="请选择"
        ></el-cascader>
      </el-form-item>
      <el-form-item v-if="[2, 3].includes(form.type)" :label="typeLabel + '部门'" prop="processDepartmentCode">
        <el-row>
          <el-col :span="12" style="padding-right: 10px">
            <el-form-item>
              <el-cascader style="width: 100%" ref="areaCascader" v-model="form.addressId" :props="{ children: 'subList', label: 'name', value: 'id', expandTrigger: 'hover', emitPath: false, checkStrictly: true }" :options="areas" :show-all-levels="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-cascader
                placeholder="请选择部门"
                ref="cascader"
                v-model="form.processDepartmentCode"
                :props="{ label: 'name', value: 'code', expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
                :options="departmentTree"
                :show-all-levels="false"
                @change="$refs.cascader && $refs.cascader.toggleDropDownVisible(false)"
                style="width: 100%"
                :key="cascaderIndex"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item :label="typeLabel + '备注'" prop="comment2">
        <el-input v-model="form.comment2" show-word-limit maxlength="300" placeholder="请输入详细描述" type="textarea" :autosize="{ minRows: 7 }"></el-input>
      </el-form-item>
      <el-form-item label="案件抄送" prop="departments" :rules="form.type === 1 ? [{ required: true, message: '请选择案件抄送单位' }] : [{ required: false }]">
        <el-checkbox v-model="form.checked">案件抄送以下单位：</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="12">
            <el-cascader ref="cascader2" :props="{ label: 'name', value: 'code', expandTrigger: 'hover', emitPath: false, checkStrictly: true }" :options="departmentTree2" v-model="form.dept" :show-all-levels="false"></el-cascader>
          </el-col>
          <el-col :span="12"><el-button type="primary" @click="onAdd" icon="el-icon-plus">添加抄送部门</el-button></el-col>
        </el-row>
        <el-table v-if="form.departments.length" :data="form.departments">
          <el-table-column type="index" label="编号" width="60"></el-table-column>
          <el-table-column prop="name" label="单位名称" width="240"></el-table-column>
          <el-table-column prop="address" label="抄送备注">
            <template slot-scope="{ row }">
              <el-input v-model="row.remark" placeholder="请输入给本部门的抄送信息"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="120">
            <template slot-scope="row">
              <el-button style="flex-shrink: 0" @click="onDel(row.$index)" type="text" plain>取消抄送</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div class="split"></div>

    <div class="dialog-footer-btn">
      <el-button @click="handleClose" type="primary" plain>关闭</el-button>
      <el-button @click="handleSubmit" :loading="submitting" type="primary">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as mixins from "@/utils/mixins";
import * as workOrderApi from "@/api/workOrder/index";
import * as templateApi from "@/api/template";
import { department2Tree, forEachTree, removeEmptyWithTree } from "@/utils/common";
import * as administrativeDivisionAPI from "@/api/administrativeDivision";
import { mapState } from "vuex";

export default {
  name: "acceptAndTransferDialog",
  mixins: [mixins.dialog, mixins.form],
  props: ["visible", "workOrderNo", "itemCode"],
  data() {
    return {
      form: {
        type: 0,
        checked: false,
        processDepartmentCode: "",
        processDepartmentName: "",
        comment2: "",
        dept: "",
        addressId: "",
        departments: [],
      },
      rules: {
        comment2: [{ required: true, message: "请填写" }],
        processDepartmentCode: [{ required: true, message: "请选择" }],
        type: [{ required: true, message: "请选择" }],
      },
      submitting: false,
      departmentTree: [],
      departmentTree2: [],
      cascaderIndex: 0,
      typeLabel: "直办",
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  watch: {
    "form.type"(type) {
      this.form.addressId = "";
      this.form.processDepartmentCode = "";
      this.cascaderIndex = 0;
      if (this.form.type === 1) {
        workOrderApi.all.departmentTree().then((res) => {
          this.departmentTree = forEachTree(department2Tree(res.result, false), (a) => {
            if (a.code === this.userInfo.orgCode) {
              a.disabled = true;
            }
          });
        });
      }
      // 查询备注模版
      /*
        直办备注	1014
        转办备注	1015
        交办备注	1001
        指定办理备注	1016
      */
      switch (String(this.form.type)) {
        case "0":
          this.typeLabel = "直办";
          this.getMarkTemp(1014);
          break;
        case "1":
          this.typeLabel = "转办";
          this.getMarkTemp(1015);
          break;
        case "2":
          this.typeLabel = "交办";
          this.getMarkTemp(1001);
          break;
        case "3":
          this.typeLabel = "指定办理";
          this.getMarkTemp(1016);
          break;

        default:
          break;
      }
    },
    "form.addressId"(addressId) {
      if (!addressId) return;
      administrativeDivisionAPI
        .getDepartmentTreeByArea({ administrativeId: addressId })
        .then((r) => {
          this.cascaderIndex++;
          let data = JSON.parse(JSON.stringify(r.result));
          removeEmptyWithTree(data);
          this.departmentTree = data;
        })
        .finally(() => {});
    },
  },
  methods: {
    onDel(index) {
      this.form.departments.splice(index, 1);
    },
    onAdd() {
      const node = this.$refs.cascader2.getCheckedNodes()[0];
      if (node) {
        const existNode = this.form.departments.find((a) => a.code === node.data.code);
        if (existNode) {
          existNode.del = false;
        } else {
          this.form.departments.push({
            name: node.data.name,
            code: node.data.code,
            remark: "",
            new: true,
            del: false,
          });
        }
        this.$refs.cascader2.handleClear();
      }
    },
    show() {
      this.getMarkTemp(1014);
      workOrderApi.distribute.area().then((res) => {
        this.areas = [res.result];
      });
      workOrderApi.all.departmentTree().then((res) => {
        this.departmentTree = forEachTree(department2Tree(res.result, false), (a) => {
          if (a.code === this.userInfo.orgCode) {
            a.disabled = true;
          }
        });
        this.departmentTree2 = forEachTree(department2Tree(res.result, false), (a) => {
          if (a.code === this.userInfo.orgCode) {
            a.disabled = true;
          }
          if (a.code === this.form.processDepartmentCode) {
            a.disabled = true;
          }
        });
      });
    },
    getMarkTemp(code) {
      /*
        直办备注	1014
        转办备注	1015
        交办备注	1001
        指定办理备注	1016
      */
      templateApi.detailByCode(code).then((res) => {
        this.form.comment2 = res.result.value;
      });
    },
    handleSubmit() {
      this.validateAndConfirm("form")
        .then((res) => {
          this.submitting = true;
          var params = {
            workOrderNo: this.workOrderNo,
            type: this.form.type,
            comment: this.form.comment2,
            processDepartmentCode: this.form.processDepartmentCode,
          };
          if (this.$refs.cascader) {
            const checkedNode = this.$refs.cascader.getCheckedNodes()[0];
            params.processDepartmentName = checkedNode ? checkedNode.data.name : "";
          }
          if (this.form.checked) {
            params.departmentDtoList = this.form.departments.map((item) => {
              return {
                departmentCode: item.code,
                departmentName: item.name,
                remark: item.remark,
              };
            });
            // params.pushDepartmentCode = this.departments.map((a) => a.code).join(";");
            // params.pushDepartmentName = this.departments.map((a) => a.name).join(";");
          }
          return workOrderApi.all.acceptance(params);
        })
        .then(() => {
          this.$emit("success");
          this.handleClose();
        })
        .finally(() => {
          this.submitting = false;
        });
    },
    removeChild(arr) {
      arr.forEach((item) => {
        if (item.children && item.children.length > 0) {
          this.removeChild(item.children);
        } else if (!item.children.length) {
          delete item.children;
        }
      });
      // console.log("arr :>> ", arr);
    },
  },
};
</script>

<style scoped lang="less">
.el-cascader {
  width: 100%;
}
.el-table {
  margin-top: 20px;
}
/deep/.el-radio__input {
  transform: scale(1.1);
}
/deep/.el-radio__label {
  font-size: 16px;
}
</style>
